﻿using System;
using System.Collections.Generic;
using System.IO;
using System.IO.Ports;
using System.Linq;
using System.Text;
using System.Threading;

namespace TestRS232Scanner
{
    public class SerialPortReader
    {
        SerialPort serial;
        string value = string.Empty;

        public string Read()
        {
            try
            {
                using (serial = new SerialPort())
                {
                    //serial = new SerialPort();
                    serial.PortName = "COM1";
                    serial.BaudRate = 9600;
                    serial.Parity = System.IO.Ports.Parity.None;
                    serial.StopBits = StopBits.One;
                    serial.DataBits = 8;
                    serial.Handshake = Handshake.XOnXOff;
                    serial.Open();
                    var tmp = serial.ReadLine().TrimEnd('\r').Split(';');
                    value = tmp[tmp.Length];
                    using (var sw = new StreamWriter("log.csv", true))
                    {
                        sw.Write(value);
                    }
                    Thread.Sleep(100);
                    serial.Close();
                }
            }
            catch (Exception ex)
            {
                value = ex.Message;
            }
            return value;
        }

        public void Write()
        {
            try
            {
                using (serial = new SerialPort())
                {
                    //serial = new SerialPort();
                    serial.PortName = "COM1";
                    serial.BaudRate = 9600;
                    serial.Parity = System.IO.Ports.Parity.None;
                    serial.StopBits = StopBits.One;
                    serial.DataBits = 8;
                    serial.Handshake = Handshake.XOnXOff;
                    serial.Open();

                    serial.WriteLine("");

                    /*
                    value = serial.ReadLine().TrimEnd('\r');
                    using (var sw = new StreamWriter("log.csv", true))
                    {
                        sw.Write(value);
                    }
                     * */
                    Thread.Sleep(100);
                    serial.Close();
                }
            }
            catch (Exception ex)
            {
                value = ex.Message;
            }


        }

    }
}
